import {
  getSimilarSongApi,
  getSongCommentApi,
  getSongDetailApi
} from '@/server/modules'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

// 根据id获得歌曲详情
export const fetchSongDetailAction = createAsyncThunk(
  'getSongDetailAction',
  async (id: number, { dispatch }) => {
    const res: any = await getSongDetailApi(id)
    dispatch(setSongDetail(res.songs[0]))
  }
)

// 获得歌曲评论信息
export const fetchSongCommentAction = createAsyncThunk(
  'getSongCommentAction',
  async (data: object, { dispatch }) => {
    const res: any = await getSongCommentApi(data)
    dispatch(setCommentList(res.comments))
    dispatch(setCommentTotal(res.total))
  }
)

// 获得相似歌曲信息
export const fetchSongSimiAction = createAsyncThunk(
  'fetchSongSimiAction',
  async (id: number, { dispatch }) => {
    const res: any = await getSimilarSongApi({ id })
    dispatch(setSimiSongList(res.songs))
  }
)

interface IState {
  songDetail: object
  commentTotal: number
  commentList: Array<any>
  similarSongList: Array<any>
}

const initialState: IState = {
  songDetail: {}, // 歌曲详情
  commentTotal: 0, // 评论总数
  commentList: [], // 评论列表
  similarSongList: [] // 相似歌曲列表
}

const songDetailSlice = createSlice({
  name: 'songDetail',
  initialState,
  reducers: {
    setSongDetail(state, action) {
      state.songDetail = action.payload
    },
    setCommentList(state, action) {
      state.commentList = action.payload
    },
    setCommentTotal(state, action) {
      state.commentTotal = action.payload
    },
    setSimiSongList(state, action) {
      state.similarSongList = action.payload
    }
  }
})

export const {
  setSongDetail,
  setCommentList,
  setCommentTotal,
  setSimiSongList
} = songDetailSlice.actions

export default songDetailSlice.reducer
